<template>
    <n-card :bordered="false" class="proCard">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
        </template>
        </BasicForm>
        <BasicTable title="课程列表" titleTooltip="niconiconi" :columns="columns" :request="loadDataTable"
            :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
            :row-class-name="rowClassName" @update:checked-row-keys="onCheckedRow">
            <template #tableTitle>
                <n-button type="primary" @click="addTable">
                    <template #icon>
                        <n-icon>
                            <PlusOutlined />
                        </n-icon>
                    </template>
                    新建
                </n-button>
            </template>
            <template #toolbar>
                <n-button type="primary" @click="reloadTable">刷新数据</n-button>
            </template>
        </BasicTable>
        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="title">
            <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80"
                class="py-4">
                <n-form-item label="课程名" path="courseName">
                    <n-input placeholder="请输入课程名" v-model:value="formParams.courseName" />
                </n-form-item>
                
                <n-form-item label="工号" path="TID">
                    <n-input type='year' :readonly="isReadOnly" format='yyyy' placeholder="请输入工号" v-model:value="formParams.TID" /><n-button @click="handleCheckTeacher" >查询教师名</n-button>
                </n-form-item>
                <n-form-item label="教师名" path="teacherName">
                    <n-input readonly placeholder="" v-model:value="formParams.teacherName" />
                </n-form-item>
            </n-form>
            <template #action>
                <n-space>
                    <n-button @click="() => (showModal = false)">取消</n-button>
                    <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
                </n-space>
            </template>
        </n-modal>
    </n-card>
</template>
<script lang="ts" setup>
import { reactive, ref, h } from 'vue';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getTableList } from '@/api/manager/courseManage/list';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './teacher';
import { PlusOutlined } from '@vicons/antd';
import {  useDialog, useMessage } from 'naive-ui';
import { http } from '@/utils/http/axios';
import { useRouter } from 'vue-router';

const params = reactive({
    pageSize: 10
});
const showModal = ref(false);
const rules = [];
const formParams :any= reactive({
    courseName: null,
    TID: null,
    teacherName: null
});
const formRef = ref();
const formBtnLoading = ref(false);
const title = ref("");
const isReadOnly = ref(false);
const message = useMessage();
const dialog = useDialog();
const router = useRouter();

function confirmForm(e){
    e.preventDefault();
        formBtnLoading.value = true;
        formRef.value.validate((errors) => {
            if (!errors) {
            //message.success('新建成功');
            let params = formParams;
            let url = '';
            if(title.value == "新建"){
                url = '/manager/course_manage/addCourse' 
            }else{
                url = '/manager/course_manage/editCourse'
            }
            http.request({
                url: url,
                method: 'post',
                params
            }).then(
                () => {
                message.success('成功');
                showModal.value = false;
                reloadTable();
                }
            );
            } else {
            message.error('请填写完整信息');
            }
            formBtnLoading.value = false;
        });
}

const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
};

async function handleCheckTeacher(){
    if(formParams['TID'] == null){
        message.error('请填写教师工号');
        return;
    }
    let teacherInfo = await http.request({
                url: '/manager/teacher_manage/getTeacherName',
                method: 'get',
                params: {TID:formParams['TID']}
            });
    formParams['teacherName'] = teacherInfo.academyName+' ' + teacherInfo['name'];
}

const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
        return h(TableAction, {
            style: 'button',
            actions: createActions(record),
        });
    },
});

function handleDelete(record) {
    dialog.info({
        title: '提示',
        content: `您想删除${record.courseName}`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            //message.success('删除成功');
            let getparam = {};
            let url="/manager/course_manage/deleteCourse";
            getparam['courseID'] = record['courseID'];
            http.request({
                url: url,
                method: 'get',
                params: getparam
            }
            ).then(
                () => {
                    message.success('成功');
                    reloadTable();
                }
            );
        },
        onNegativeClick: () => { },
    });
}

function handleEdit(row) {
    formParams.courseID = row.courseID;
    formParams.courseName = row.courseName;
    formParams.TID = row.TID;
    formParams.teacherName = row.name;
    title.value = '修改';
    isReadOnly.value = true;
    showModal.value = true;
}

function rowClassName(row) {
    console.log(row);
    if (row.majorList != null) {
        return '';
    } else {
        return 'leaf-row'
    }
}

function createActions(record) {
    return [
        {
            label: '学生列表',
            onClick: handleStudentDetail.bind(null,record),
            ifShow: () => {
                return true;
            },
            auth: ['basic_list'],
        },
        {
            label: '修改',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
                return true;
            },
            auth: ['basic_list'],
        }, {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['basic_list'],
        },

    ];
}
const actionRef = ref();
function onCheckedRow() {

}
function addTable() {
    formParams.claseID = null;
    formParams.claseName = null;
    formParams.majorID = null;
    formParams.enterYear = null;
    title.value = '新建';
    isReadOnly.value = false;
    showModal.value = true;

}
function reloadTable() {
    actionRef.value.reload();
}

const schemas: FormSchema[]=[
    {
        field: 'courseName',
        component:'NInput',
        label:'课程名',
        componentProps:{
            placeholder: '请输入课程名',
            onClear:()=>{
                params['courseName'] = null;
            }
        }
    },
    {
        field: 'TID',
        component: 'NInput',
        label: '教师工号',
        componentProps: {
            placeholder: '请输入工号',
            onClear:()=>{
                params['TID'] = null;
            }
        }
  }
];

const [register,{}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
  labelWidth: 80,
  schemas,
});

function handleStudentDetail(values: Recordable){
    router.push({name:'manager_courseManage_student',params: {courseID :values['courseID'],courseName :values['courseName']}});
}

function handleSubmit(values: Recordable) {
  params['courseName'] = values['courseName'];
  params['TID'] = values['TID'];
  reloadTable();
}

function handleReset(values: Recordable) {
  console.log(values);
}

</script>